<template>
  <div>
    <el-dialog
      :model-value="props.dialogVisible"
      :title="props.formStatus === 1 ? '编辑产品' : '新增产品'"
      width="800px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-form ref="productFormRef" :model="productForm" :rules="productFormRules" label-width="100px" @submit.prevent>
        <el-form-item label="产品名称：" prop="name">
          <el-input v-model="productForm.name" :maxlength="20" clearable placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="规格型号：" prop="mode">
          <el-input v-model="productForm.mode" :maxlength="20" clearable placeholder="请输入规格型号"></el-input>
        </el-form-item>
        <el-form-item label="产品海报：" prop="poster">
          <el-upload
            class="avatar-uploader"
            accept=".jpg, .png"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="changeFile">
            <img v-if="productForm.poster" :src="productForm.poster" class="avatar"/>
            <e-icon v-else type="Plus" :size="28" class="avatar-uploader-icon"></e-icon>
            <!-- <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon> -->
          </el-upload>
        </el-form-item>
        <el-form-item label="产品介绍：" prop="info">
          <div style="border: 1px solid #ccc;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="{
                excludeKeys: ['group-image', 'group-video']
              }"/>
            <Editor
              style="height: 300px; overflow-y: hidden;"
              v-model="productForm.info"
              :defaultConfig="editorConfig"
              @onCreated="handleCreated"/>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit(productFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ProductModifyForm">
import { ref, shallowRef, reactive, watch, ComponentInternalInstance, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import EIcon from '@/components/e-icon/e-icon.vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { productInsert, productUpdate } from '@/api/product-manage'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formStatus: {
    type: Number,
    default: 0
  },
  formData: {
    type: Object,
    default: {}
  }
})

const productForm = reactive({
  productId: -1,
  name: '',
  mode: '',
  poster: <any>'',
  info: ''
})
const productFormRef = ref<FormInstance>()
const productFormRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入产品名称！' }
  ],
  poster: [
    { required: true, message: '请上传产品海报！' }
  ],
})
const editorRef = shallowRef()
const editorConfig = { placeholder: '请输入内容...' }

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    if (props.formStatus === 1) {
      productForm.productId = props.formData.productId
      productForm.name = props.formData.name
      productForm.mode = props.formData.mode
      productForm.info = props.formData.info
      productForm.poster = props.formData.poster
    }
  }
})

// 上传改变事件
const changeFile = (file: any) => {
  if (file.raw.size / 1024 / 1024 > 16) {
    ElMessage.error('上传图片不能超过 16MB！')
    return false
  }
  if (file.raw.type !== 'image/jpeg' && file.raw.type !== 'image/png') {
    ElMessage.error('上传图片格式必须为 jpg 或 png！')
    return false
  }
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    // console.log(reader.result)
    productForm.poster = reader.result
    productFormRef.value?.validateField('poster')
  }
}

// 记录 editor 实例
const handleCreated = (editor: any) => {
  editorRef.value = editor
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  resetForm(productFormRef.value)
  proxy?.$emit('update:dialogVisible', false)
}

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      if (props.formStatus === 0) {
        let { productId, ...params } = productForm
        await productInsert(params).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success(`新增成功！`)
            emit('submit')
            handleClose()
          } else {
            ElMessage.error(`${res.msg}`)
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        let params = Object.assign({}, productForm)
        await productUpdate(params).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success(`编辑成功！`)
            emit('submit')
            handleClose()
          } else {
            ElMessage.error(`${res.msg}`)
          }
        }).catch(err => {
          console.log(err)
        })
      }
    }
  })
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="stylus" scoped>

.avatar-uploader
  .avatar
    width 178px
    height 178px
    display block
  &:deep(.el-upload)
    border 1px dashed var(--el-border-color)
    border-radius 6px
    cursor pointer
    position relative
    overflow hidden
    transition var(--el-transition-duration-fast)
    &:hover
      border-color var(--el-color-primary)
  .avatar-uploader-icon
    // font-size 28px
    color #8c939d
    width 178px
    height 178px
    text-align center
</style>
